package com.liu.controller;

import com.liu.dto.Result;
import com.liu.pojo.User;
import com.liu.util.HttpServletFactory;
import com.liu.util.LoggerFactory;
import com.liu.util.Page;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author 老刘Matthew
 * @Timestamp 2022/7/14 22:05
 * @Description
 */
@WebServlet("/main/*")
@MultipartConfig
public class EntranceServlet extends GenericServlet implements HttpServletFactory, LoggerFactory {

    private static final long serialVersionUID = 1L;

    private Class<? extends GenericServlet> clazz = this.getClass();

    /**
     * 分发处理 /main/doLogin 二级请求
     */
    public void _doLogin(HttpServletRequest request, HttpServletResponse response) {

//        super.enableAjax();

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        logger.info("----------> _doLogin : " + request.getRequestURI());

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkbox = request.getParameter("checkbox");

        try {

            User user = userDao.queryByUsername(username);

            Boolean status =
                    null != user && /* 短路赋值 */
                    password.equals(user.getPwd());

            Result result = new Result().setStatus(status);

            if (status) {
                result.setMessage("登录成功！");

                // 创建session
                HttpSession session = request.getSession();
                session.setAttribute("user", user);

                // Server 维护 Session 副本，后端复用
                super.setSessionUser(user);
                super.setSession(session);

                if (checkbox != null) {
                    Cookie ckna = new Cookie("name", username);
                    ckna.setMaxAge(60 * 60 * 24 * 30);
                    Cookie ckpwd = new Cookie("password", password);
                    ckpwd.setMaxAge(60 * 60 * 24 * 30);// cookie有效期30天
                    response.addCookie(ckna);// 将用户name发送给客服端
                    response.addCookie(ckpwd);
                }

            } else
                result.setMessage("登录失败，请检查账号密码！");

//            new GenericServletBuilder(request, response, clazz)
//                .setAjax(true)
//                .build()
//                .getRequestMapping(gson.toJson(result));

            response.getWriter().print(gson.toJson(result));

        } catch (Exception e) {
            logger.error("doLogin 登录方法异常！", e);
        }
    }

    public void _doLogout(HttpServletRequest request, HttpServletResponse response) {

        try {

            // 清空 Session 及页面变量
            if (getSessionUser() != null) {
                setSessionUser(null);
                request.getSession().removeAttribute("user");
            }

            if (getSession() != null) {
                setSession(null);
                request.getSession().invalidate();
            }


            new GenericServletBuilder(request, response, clazz)
                .setUrl(Page.INDEX.get())
                .build()
                .getRequestMapping();

        } catch (Exception e) {
            logger.error("doLogin 退出会员中心方法异常！", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

        doPost(request, response, this.getClass());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {

        /**
         * GenericServlet 托管 doPost(HttpServletRequest request, HttpServletResponse response) 入口方法
         * 二级方法由反射机制备动调用，实现 JSP/Servlet 下二级请求
         * 为大三阶段学生讲解 Spring/SpringMVC 分层转发机制作铺垫
         */
        doPost(request, response, this.getClass());
    }

}
